package cn.wenzy.aurora.admin.oauth2.userdetails;

import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class SysUserCache implements UserCache {

    private Cache<String, String> cache = Caffeine.newBuilder()
            .expireAfterWrite(Duration.ofMinutes(30))
            .initialCapacity(128)
            .maximumSize(2048)
            .build();

    @Override
    public UserDetails getUserFromCache(String username) {
        String password = cache.getIfPresent(username);
        if (StrUtil.isNotBlank(password)) {
            return User.withUsername(username)
                    .password(password)
                    .authorities(AuthorityUtils.NO_AUTHORITIES)
                    .build();
        }
        return null;
    }

    @Override
    public void putUserInCache(UserDetails user) {
        cache.put(user.getUsername(), user.getPassword());
    }

    @Override
    public void removeUserFromCache(String username) {
        cache.invalidate(username);
    }
}
